﻿//
// Copyright (C) Ashish Kaila 2011
//

using System;
using System.Collections.Generic;
using System.Windows.Threading;
using Flipbook.ViewModels;
using MixModes.Synergy.Utilities;

namespace Flipbook
{
    /// <summary>
    /// Interaction logic for AnimationWindow.xaml
    /// </summary>
    public partial class AnimationWindow
    {
        public AnimationWindow(IEnumerable<CanvasViewModel> canvasViewModels, int frameRate)
        {
            InitializeComponent();
            Validate.Assert<ArgumentException>(frameRate > 0);
            CanvasViewModels = new List<CanvasViewModel>(canvasViewModels);
            _timer = new DispatcherTimer(DispatcherPriority.Render);
            _timer.Interval = TimeSpan.FromSeconds(1/(double)frameRate);
            _timer.Tick += DisplayFrame;
            _currentIndex = 0;
            _initialIndex = 0;
            _lastIndex = CanvasViewModels.Count;
            Loaded += (a, b) => _timer.Start();
        }

        public AnimationWindow(IEnumerable<CanvasViewModel> canvasViewModels, int frameRate, int initialIndex)
        {
            InitializeComponent();
            Validate.Assert<ArgumentException>(frameRate > 0);
            CanvasViewModels = new List<CanvasViewModel>(canvasViewModels);
            _timer = new DispatcherTimer(DispatcherPriority.Render);
            _timer.Interval = TimeSpan.FromSeconds(1 / (double)frameRate);
            _timer.Tick += DisplayFrame;
            _initialIndex = initialIndex;

            if (_initialIndex + 2 < CanvasViewModels.Count) _lastIndex = _initialIndex + 3;
            else _lastIndex = CanvasViewModels.Count;

            _currentIndex = _initialIndex;
            Loaded += (a, b) => _timer.Start();
        }

        
        /// <summary>
        /// Gets or sets the canvas view models.
        /// </summary>
        /// <value>
        /// The canvas view models.
        /// </value>
        private List<CanvasViewModel> CanvasViewModels
        {
            get; 
            set;
        }

        /// <summary>
        /// Displays the frame.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void DisplayFrame(object sender, EventArgs e)
        {
            if (_currentIndex >= _lastIndex)
            //if (_currentIndex >= CanvasViewModels.Count)
            {
                _timer.Stop();
                Close();
                return;
            }

            CanvasViewModel canvasViewModel = CanvasViewModels[_currentIndex++];
            Canvas.Strokes = canvasViewModel.Canvas.Strokes.Clone();
        }

        // Private members
        private readonly DispatcherTimer _timer;
        private int _currentIndex;
        private int _initialIndex;
        private int _lastIndex;
    }
}
